package com.fs.book.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局的异常处理器
 */
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    /**
     * 处理异常
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 产生异常的处理器对象:  Controller方法对象
     * @param ex 产生的异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        //1.判断异常类型   系统异常     业务异常
        if(ex instanceof  BookBaseException ){ //业务异常
            //2. 如果是系统异常, 响应 "系统忙,请稍后再试!"   如果业务异常: 响应异常信息
            modelAndView.addObject("error",ex.getMessage());
        }else{ //系统异常
            modelAndView.addObject("error","系统忙,请稍后再试!");
        }
        //3.设置错误页面
        modelAndView.setViewName("/error");
        return modelAndView;
    }
}
